package org.zoomdev.zoom.dao.ddl.utils;

import org.zoomdev.zoom.dao.DaoException;
import org.zoomdev.zoom.dao.meta.ColumnTypeMeta;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public final class MetaUtils {
    public static List<String> getAllTableNames(Connection conn) throws SQLException {
        List<String> tables = new ArrayList<>();
        DatabaseMetaData metaData = conn.getMetaData();

        try (ResultSet rs = metaData.getTables(conn.getCatalog(), null, "%", new String[]{"TABLE"})) {
            while (rs.next()) {
                tables.add(rs.getString("TABLE_NAME"));
            }
        }
        return tables;
    }


    public static ColumnTypeMeta[] getColumnTypes(Connection conn, String table) throws SQLException {
        try (Statement st = conn.createStatement()) {
            try (ResultSet rs = st.executeQuery("select * from " + table + " where 1=0")) {
                ResultSetMetaData rd = rs.getMetaData();
                int c = rd.getColumnCount();
                ColumnTypeMeta[] metas = new ColumnTypeMeta[c];
                for (int i = 0; i < c; ++i) {
                    int index = i + 1;
                    String className = rd.getColumnClassName(index);
                    Class<?> type = Class.forName(className);
                    String name = rd.getColumnName(index);
                    int jdbcType = rd.getColumnType(index);
                    metas[i] = new ColumnTypeMeta(name, type, jdbcType);
                }
                return metas;
            } catch (ClassNotFoundException e) {
                throw new DaoException(e);
            }
        }
    }
}
